#include "EditProfileDialog.h"

EditProfileDialog::EditProfileDialog(QWidget *parent)
    : QDialog{parent}
{
    setFixedWidth(500);

    setWindowTitle("编辑资料");

    QVBoxLayout *layout = new QVBoxLayout(this);

    // 头像预览和更改按钮
    avatarPreview = new AvatarLabel(this);
    avatarPreview->setFixedSize(120, 120);
    QHBoxLayout *avatarLayout = new QHBoxLayout();
    avatarLayout->addWidget(avatarPreview);
    avatarLayout->setAlignment(avatarPreview, Qt::AlignCenter); // 设置该控件居中

    changeAvatarButton = new QPushButton("更换头像");
    layout->addLayout(avatarLayout);
    layout->addWidget(changeAvatarButton);

    // 用户名输入框
    usernameEdit = new QLineEdit("未知用户");
    layout->addWidget(new QLabel("用户名"));
    layout->addWidget(usernameEdit);

    // 个性签名输入框
    signatureEdit = new QTextEdit("个性签名");
    signatureEdit->setFixedHeight(50);
    signatureEdit->setAcceptRichText(false); // 纯文本模式
    layout->addWidget(new QLabel("个性签名"));
    layout->addWidget(signatureEdit);

    // 保存按钮
    saveButton = new QPushButton("保存");
    layout->addWidget(saveButton);

    connect(changeAvatarButton, &QPushButton::clicked, [this]()
            {
        QString filePath = QFileDialog::getOpenFileName(this, "选择头像", "", "图片文件 (*.png *.jpg *.bmp)");
        if (!filePath.isEmpty()) {
            updatedAvatar = QPixmap(filePath);
            avatarPreview->setPixmap(updatedAvatar);
        } });

    connect(saveButton, &QPushButton::clicked, this, &EditProfileDialog::onSaveButtonClicked);

    setStyleSheet(R"(
        QDialog {
            background-color: #ffffff;
        }
        QPushButton {
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 5px;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
        QLineEdit, QTextEdit {
            border: 1px solid #ccc;
            padding: 4px;
        }
    )");
}

void EditProfileDialog::onSaveButtonClicked()
{
    if (usernameEdit->text().isEmpty())
    {
        QMessageBox::warning(this, "错误", "用户名不能为空");
        return;
    }

    // 发送更新完成信号，并携带头像、用户名、个性签名
    emit profileUpdated(updatedAvatar, usernameEdit->text(), signatureEdit->toPlainText());

    accept(); // 关闭对话框
}
